package com.hanbang.cxgz_2.utils.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.IBinder;
import android.provider.MediaStore;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.DatePicker;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.NumberPicker;
import android.widget.TextView;

import com.hanbang.cxgz_2.R;
import com.hanbang.cxgz_2.appliction.MyApplication;
import com.hanbang.cxgz_2.utils.other.ObjectUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.hanbang.cxgz_2.appliction.MyApplication.myApp;

public class UiUtils {

    public static void setColorSchemeResources(SwipeRefreshLayout swipeRefreshLayout) {
        swipeRefreshLayout.setColorSchemeResources(R.color.SwipeRefreshLayout_1, R.color.SwipeRefreshLayout_2, R.color.SwipeRefreshLayout_3, R.color.SwipeRefreshLayout_4);
    }

    public static void setRefreshing(final SwipeRefreshLayout swipeRefreshLayout, final boolean b) {

        swipeRefreshLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(b);
            }
        }, 400);

    }

    /**
     * 获得一个空间的宽高   防0
     */

    public static void setViewMeasure(View view) {
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
    }

    /**
     * 获得一个空间的宽   防0
     */

    public static void setViewWidth(View view) {
        setViewMeasure(view);
        view.getMeasuredWidth();
    }

    public static void setViewHeight(View view) {
        setViewMeasure(view);
        view.getMeasuredHeight();
    }

    /**
     * 从资源文件获取一个view
     */
    public static View getInflaterView(Context context, int res) {
        View view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(res, null);
        applyFont(view);
        return view;
    }

    /**
     * 从资源文件获取一个view
     */
    public static View getInflaterView(Context context, int res, ViewGroup parent) {
        View view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(res, parent);
        applyFont(view);
        return view;
    }

    /**
     * 从资源文件获取一个view
     */
    public static View getInflaterView(Context context, int res, ViewGroup parent, boolean attachToRoot) {
        View view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(res, parent, attachToRoot);
        applyFont(view);
        return view;
    }


    public static void setButtonEnabled(ViewGroup ll, boolean enabled) {
        ll.setEnabled(enabled);
        for (int i = 0; i < ll.getChildCount(); i++) {
            View child = ll.getChildAt(i);
            if (child instanceof ViewGroup) {
                setButtonEnabled((ViewGroup) child, enabled);
            } else {
                child.setEnabled(enabled);
            }
        }
    }


    /**
     * 设置按钮的点击效果  只能设置ImageView  和TextView
     */
    public static void setButtonClickTint(final View view, final int colorUp,
                                          final int colorDown) {
        view.setClickable(true);
        if (view instanceof ImageView) {
            view.setOnTouchListener(new OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            ((ImageView) view).setColorFilter(view.getResources()
                                    .getColor(colorDown));
                            break;
                        case MotionEvent.ACTION_CANCEL:
                        case MotionEvent.ACTION_UP:
                            ((ImageView) view).setColorFilter(view.getResources()
                                    .getColor(colorUp));
                            break;

                        default:
                            break;
                    }

                    return false;
                }
            });
            // 设置字体点击后的文字颜色变化
        } else if (view instanceof TextView) {
            view.setOnTouchListener(new OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {

                        case MotionEvent.ACTION_DOWN:

                            ((TextView) view).setTextColor(view.getResources()
                                    .getColor(colorDown));
                            break;
                        case MotionEvent.ACTION_CANCEL:
                        case MotionEvent.ACTION_UP:
                            ((TextView) view).setTextColor(view.getResources()
                                    .getColor(colorUp));
                            break;

                        default:
                            break;
                    }

                    return false;
                }
            });
        } else if (view instanceof ViewGroup) {
            view.setOnTouchListener(new OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            setViewGroupTint((ViewGroup) v, colorDown);
                            break;
                        case MotionEvent.ACTION_CANCEL:
                        case MotionEvent.ACTION_UP:
                            setViewGroupTint((ViewGroup) v, colorUp);
                            break;
                        default:
                            break;
                    }
                    return false;
                }
            });
        }
    }

    /*
     * 设置ImageView渲染（Tint）
     */
    public static void setImageViewTint(final ImageView view, final int color) {
        view.setColorFilter(view.getResources().getColor(color));
    }

    /*
    * 设置ViewGroup渲染（Tint）
    */
    public static void setViewGroupTint(ViewGroup view, int color) {
        for (int i = 0; i < view.getChildCount(); i++) {
            View child = view.getChildAt(i);
            if (child instanceof ImageView) {
                setImageViewTint((ImageView) child, color);
            } else if (child instanceof TextView) {
                ((TextView) child).setTextColor(view.getResources()
                        .getColor(color));
            } else if (child instanceof ViewGroup) {
                setViewGroupTint((ViewGroup) child, color);
            }
        }
    }

    /*
     * 设置字体
     */
    public static void applyFont(final View root) {
//        try {
//            if (root instanceof ViewGroup) {
//                ViewGroup viewGroup = (ViewGroup) root;
//                for (int i = 0; i < viewGroup.getChildCount(); i++)
//                    applyFont(viewGroup.getChildAt(i));
//            } else if (root instanceof TextView)
//
////                ((TextView) root).setTypeface(MyApplication.myApp.typeface);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    public static View getRootView(Activity context) {
        return context.getWindow().getDecorView()
                .findViewById(android.R.id.content);
    }

    public static View getDecorView(Activity context) {
        return context.getWindow().getDecorView();
    }

    /*
     * 设置按钮点击后的渲染（Tint）
     */
    public static void setButtonClickTint(final ImageView view,
                                          final int colorUp, final int colorDown) {
        view.setOnTouchListener(new OnTouchListener() {

            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        view.setColorFilter(view.getResources().getColor(colorUp));
                        break;
                    case MotionEvent.ACTION_DOWN:
                        view.setColorFilter(view.getResources().getColor(colorDown));
                        break;

                    default:
                        break;
                }

                return false;
            }
        });
    }

    /**
     * 加入购物车的动画
     */
    public static void addGwcAnim() {

    }


    /**
     * 开启拍照
     */

    public static String startPaiZhao(Activity context, int requestCode) {
        File fDir = new File(MyApplication.appSDCachePath);
        String cachePath = System.currentTimeMillis() + ".jpg";
        if (fDir.exists() || fDir.mkdirs()) {
            File cameraFile = new File(fDir, cachePath);
            if (!cameraFile.exists()) {
                try {
                    cameraFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
            context.startActivityForResult(intent, requestCode);
        }
        return cachePath;
    }

    /**
     * 开启文件选择
     * <p>
     * intent.setType(“audio/*”); //选择音频
     * intent.setType(“video/*”); //选择视频 （mp4 3gp 是android支持的视频格式）
     * intent.setType(“video/*;image/*”);//同时选择视频和图片
     */
    public static void startFileSelect(Activity context, String Type, int requestCode) {
        Intent intent = new Intent();
        intent.setType(Type);
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.putExtra("return-data", true);
        context.startActivityForResult(intent, requestCode);
    }

    /**
     * DatePicker 或者 TimePicker 调整大小
     *
     * @param tp
     */
    public static void setPikcerSize(FrameLayout tp) {
        List<NumberPicker> npList = findNumberPicker(tp);
        for (int i = 0; i < npList.size(); i++) {
            setNumberPickerSize(npList.get(i), tp instanceof DatePicker ? i == 0 : false);
            setNumberPickerInput(npList.get(i));
        }
    }

    /**
     * 调整numberpicker大小
     */
    private static void setNumberPickerSize(NumberPicker np, boolean isOne) {
        setViewMeasure(np);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(Math.round(np.getMeasuredWidth() / (isOne ? 1.2f : 2.2f)), ViewGroup.LayoutParams.WRAP_CONTENT);
        params.setMargins(ObjectUtils.dip2px(np.getContext(), 4), 0, ObjectUtils.dip2px(np.getContext(), 4), 0);
        np.setLayoutParams(params);


    }

    /**
     * 调整numberpicker显示为数字
     */
    private static void setNumberPickerInput(ViewGroup np) {
        for (int i = 0; i < np.getChildCount(); i++) {
            View v = np.getChildAt(i);
            if (v instanceof TextView) {
                ((TextView) v).setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL);
            } else if (v instanceof ViewGroup) {
                setNumberPickerInput((ViewGroup) v);
            }

        }

    }

    /**
     * 得到viewGroup里面的numberpicker组件
     *
     * @param viewGroup
     * @return
     */
    private static List<NumberPicker> findNumberPicker(ViewGroup viewGroup) {
        List<NumberPicker> npList = new ArrayList<NumberPicker>();
        View child = null;
        if (null != viewGroup) {
            for (int i = 0; i < viewGroup.getChildCount(); i++) {
                child = viewGroup.getChildAt(i);
                if (child instanceof NumberPicker) {
                    npList.add((NumberPicker) child);
                } else if (child instanceof LinearLayout) {
                    List<NumberPicker> result = findNumberPicker((ViewGroup) child);
                    if (result.size() > 0) {
                        return result;
                    }
                }
            }
        }
        return npList;
    }

    /**
     * 获得状态栏的高度
     *
     * @param context
     * @return
     */
    public static int getStatusHeight(Context context) {

        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }


    private static void exitOrShowInput(IBinder iBinder, View view) {

        InputMethodManager inputMethodManager = (InputMethodManager) myApp.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (iBinder != null) {
            inputMethodManager.hideSoftInputFromWindow(iBinder, 0);
        }
        if (view != null) {
            inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_FORCED);
        }
    }


    public static void showInput(View view) {
        exitOrShowInput(null, view);
    }

    public static void exitInput(Activity activity) {
        if (activity != null && activity.getCurrentFocus() != null) {
            exitOrShowInput(activity.getCurrentFocus().getWindowToken(), null);
        }
    }

    public static void exitInput(IBinder iBinder) {
        exitOrShowInput(iBinder, null);
    }

    public static void exitInput(View view) {
        exitOrShowInput(view.getWindowToken(), null);
    }

    public static boolean isOpenInput(Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        boolean isOpen = imm.isActive();
        return isOpen;
    }


    //============================================================================================= GridView 设置高度

    /**
     * 计算gridView高度
     *
     * @param listView
     */
    public static void setListViewHeightBasedOnChildren(GridView listView, int numColumns, int[] margin) {

        try {


            // 获取listview的adapter
            ListAdapter listAdapter = listView.getAdapter();
            if (listAdapter == null) {
                return;
            }
            // 固定列宽，有多少列
            int totalHeight = 0;
            int countItem = listAdapter.getCount();
            if (countItem > 0) {
                View listItem = listAdapter.getView(0, null, listView);
//                listItem.measure(0, 0);
                setViewMeasure(listItem);
                // 获取item的高度和
                totalHeight = listItem.getMeasuredHeight();

                totalHeight = totalHeight * (countItem / numColumns + (countItem % numColumns == 0 ? 0 : 1));
            }
            // 获取listview的布局参数
            ViewGroup.LayoutParams params = listView.getLayoutParams();
            // 设置高度
            params.height = totalHeight;


            // 设置margin
            if (margin != null && margin.length >= 4) {
                ((ViewGroup.MarginLayoutParams) params).setMargins(margin[0], margin[1], margin[2], margin[3]);

            }

            // 设置参数
            listView.setLayoutParams(params);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //=============================================================================================ListView   listView 判断上下滑动，显示与隐藏菜单


    int itemPositionStart = 0;
    int YStart;

    /**
     * listView 判断上下滑动，显示与隐藏菜单
     * 1，向上滑动隐藏
     * 2，向下滑动显示
     *
     * @param list 被监听 listView
     * @param v    要显示与隐藏的View
     */
    public void setMenuHideAndShow(final ListView list, final View... v) {
        final ListView listView = list;
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    //是流动状态
                    case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
                        itemPositionStart = view.getLastVisiblePosition();
                        if (listView.getHeaderViewsCount() == 1 && itemPositionStart == 0) {
                            YStart = Math.abs(view.getChildAt(0).getTop());
                        }
                        break;

                    //飞的状态
//                    case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
                    //闲置状态
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        int itemPositionEnd = view.getLastVisiblePosition();

                        //如果有头部并且是第一个item
                        if (listView.getHeaderViewsCount() == 1 && itemPositionEnd == 0) {
                            int YEnd = Math.abs(view.getChildAt(0).getTop());
                            if (YEnd > YStart) {
//                                MyLog.e("AAA" + "YStart==\t" + YStart + "YEnd==\t" + YEnd + "\t" + view.getListPaddingTop() + "true");
                                setViewShowAndHide(v, View.GONE);
                                return;
                            } else {
//                                MyLog.e("BBB" + "YStart==\t" + YStart + "YEnd==\t" + YEnd + "\t" + view.getListPaddingTop() + "false");
                                setViewShowAndHide(v, View.VISIBLE);
                                return;
                            }
                        }

                        //不是第一个item
                        if (itemPositionEnd > itemPositionStart) {
//                            MyLog.e("CCC" + "itemPositionStart==\t" + itemPositionStart + "\\itemPositionEnd==\t" + itemPositionEnd + "\t" + view.getListPaddingTop() + "true");
                            setViewShowAndHide(v, View.GONE);
                        } else {
//                            MyLog.e("DDD" + "itemPositionStart==\t" + itemPositionStart + "\\itemPositionEnd==\t" + itemPositionEnd + "\t" + view.getListPaddingTop() + "false");
                            setViewShowAndHide(v, View.VISIBLE);
                        }
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }

        });

    }

    /**
     * 设置view的显示与隐藏
     *
     * @param v
     * @param aaa
     */
    public static void setViewShowAndHide(View[] v, int aaa) {
        for (int i = 0; i < v.length; i++) {
            v[i].setVisibility(aaa);
        }
    }


    //======================================================================TextView 的赋值


    /**
     * 给TextView 设置文本
     */
    public static void setTextViewContent(View TextView, String content) {
        try {
            ((TextView) TextView).setText(content);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}